<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">

<script>
let token = ""
function createJsonReq(method, params) {
	return {
		jsonrpc :"2.0",
		method : method,
		id : 0,//暂时不用
		params : JSON.stringify(params)
	}
}

//登录请求的示例
let loginRequest = function ()
{
	this.jsonrpc = "2.0";
	this.method = "login.login";
	this.id = 0;//暂时不用

	let params = {};
	params.uid = 111
	this.params = JSON.stringify(params);
}

//登录请求的示例
let goldRankRequest = function ()
{
	this.jsonrpc = "2.0";
	this.method = "rank.goldRank";
	this.id = 0;//暂时不用

	let params = {};
	params.num = 10
	this.params = JSON.stringify(params);
}

//解析返回结果的样子,content为http/websocket返回的字符串
function parseJsonRpc ( content )
{
	try
	{
		obj = JSON.parse(content);
		if ( obj.result )
		{
			let result = JSON.parse(obj.result);
			if ( 0 == result.code )
			{
				return result;
			}
			else
			{
				//这是业务错误？
				console.log(result);
			}
		}
	}
	catch(e)
	{
		console.error(e);
	}

	//这是网关错误,不是业务错误
	if ( obj.error)
	{
		console.log(obj.error.code,obj.error.message,obj.error.data);
	}
	
	return null;
}





let addr = "http://127.0.0.1:8080/api"
function login()
{
	let http = new XMLHttpRequest();

	let url = addr + "/login";
	http.open("post", url, true);
	
	//这种写法没试过
	//http.setRequestHeader("Content-type", "application/json;charset=utf-8");
	
	//html5中如下写
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			let result = parseJsonRpc(http.responseText);
			if ( result )
			{
				
				token = result.token

				console.log("登陆成功:", token)			
			}
		}
	}
	let req = new loginRequest();
	let postData = JSON.stringify(req);	
	http.send(postData);
}

function goldRank()
{
	let http = new XMLHttpRequest();

	let url = addr + "/rank";
	http.open("post", url, true);
	
	//这种写法没试过
	// http.setRequestHeader("Content-type", "application/json;charset=utf-8");
	
	//html5中如下写
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//TODO 后续要加 token
	// http.setRequestHeader("X-Token",111);

	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			let result = parseJsonRpc(http.responseText);
			if ( result )
			{
				console.log("获取排名:", result)			
			}
		}
	}
	let req = new goldRankRequest();
	let postData = JSON.stringify(req);	
	http.send(postData);
}

</script>

</head>
<body>
<input type=button value="login" onclick="login()">
<input type=button value="获取排名" onclick="goldRank()">

<br>测试网页!
</body>
</html>